using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class LevelElevatorComponent : LevelEntityBaseComponent
    {
        public new LevelPlayRealityEntity entity { protected set; get; }
        /// <summary>
        /// 电梯的静态参数
        /// </summary>
        public EntityParamElevator elevator { protected set; get; }
        /// <summary>
        /// 电梯的当前层数
        /// </summary>
        public int floor { private set; get; }

        private int _targetFloor;
        private GameObject[] _fenceObjs;

        public override void OnCreate(TEntity entity)
        {
            this.entity = entity as LevelPlayRealityEntity;
        }

        /// <summary>
        /// 电梯实体初始化
        /// </summary>
        /// <param name="entityParamElevator"></param>
        public void InitElevatorEntity(EntityParamElevator entityParamElevator)
        {
            this.elevator = entityParamElevator;
            this._fenceObjs = new GameObject[elevator.floors.Count];
            var regionCtrl = LevelPlayModule.Instance.levelPlay.regionCtrl;
            this.floor = CalcCurFloor();
            //初始化围栏
            this._fenceObjs = regionCtrl.elevatorFenceCtrl.InitFence(entity, elevator.floors);
            //关闭当前层围栏
            _fenceObjs?[floor]?.SetActive(false);
        }

        private int CalcCurFloor()
        {
            var dynEntity = entity.GetDynLevelEntity();
            int minDis = int.MaxValue;
            int curFloor = -1;
            for (int i = 0; i < elevator.floors.Count; i++)
            {
                var floor = elevator.floors[i];
                var entityPos = new Framework.Vector3Int((int)dynEntity.x, (int)dynEntity.y, (int)dynEntity.z);
                int sqrDis = (floor.position - entityPos).sqrMagnitude;
                if (sqrDis < minDis)
                {
                    minDis = sqrDis;
                    curFloor = i;
                }
            }
            return curFloor;
        }

        public void SetTargetFloor(int floor)
        {
            this._targetFloor = floor;
        }

        public void OnMoveStateChange(bool isStopped)
        {
            if (!isStopped) //启动
            {
                //开启当前层围栏
                _fenceObjs?[floor]?.SetActive(true);
            }
            else //停止
            {
                floor = _targetFloor;
                _targetFloor = 0;
                //关闭到达层围栏
                _fenceObjs?[floor]?.SetActive(false);
            }
        }

        /// <summary>
        /// 服务器通知刷新实体数据时，如果位置发生了变化
        /// </summary>
        public void OnServiceRefreshY()
        {
            this.floor = CalcCurFloor();
            OnMoveStateChange(true);
        }

        #region ObjectPool

        public override uint MaxStore => 10;

        public override void OnPoolReset()
        {
            entity = null;
            elevator = null;
            floor = 0;
            _fenceObjs = null;
        }

        #endregion
    }
}